import 'package:f200/common/utils/index.dart';

import 'cart_item_model.dart';
import 'cart_model.dart';

extension MuTableCart on CartModel {
  CartModel addItem(CartItemModel item) {
    this.items.add(item);
    bool _allIsSelcted = true;
    for (var element in this.items) {
      if (element.isSelected == false) {
        _allIsSelcted = false;
      }
    }
    this.allIsSelected = _allIsSelcted;
    return this.copyWith();
  }

  bool existsGoodsId(String goodsId) {
    bool exists = false;
    for (var element in this.items) {
      if (element.goodsId == goodsId) {
        exists = true;
        break;
      }
    }

    return exists;
  }

  CartModel setItemQuantity(String goodsId, int quantity) {
    if (existsGoodsId(goodsId) == false) throw Exception("not found.");
    for (var element in this.items) {
      if (element.goodsId == goodsId) {
        element.quantity = quantity;
        break;
      }
    }
    return this.copyWith();
  }

  CartModel selectItem(String goodsId, bool value) {
    if (existsGoodsId(goodsId) == false) throw Exception("not found.");

    bool _allIsSelcted = true;
    for (var element in this.items) {
      if (element.goodsId == goodsId) {
        element.isSelected = value;
        if (value == false) _allIsSelcted = false;
      } else if (element.isSelected == false) {
        _allIsSelcted = false;
      }
    }
    //设置全选
    this.allIsSelected = _allIsSelcted;
    logD('----------购物车-------\n$this');
    return this.copyWith();
  }

  void selectAll(bool value) {
    for (var element in this.items) {
      element.isSelected = value;
    }
    allIsSelected = value;
  }
}
